/**
 * 子弹类
 */

export default class {
    constructor(dir = 'left',seepd = 1) {

        this.dir = dir;

        this.div = null;
        // left,top 这个属性映射到this.style.left中有利于后期获取,操作属性比操作dom性能会好点
        this.left = 0;
        this.top = 0;
        this.width = 100;
        this.height = 100;

        this.seepd = seepd;

        this.timer = 0;
        this.onmove = function(){};
    }
    draw(wrap){
        this.div = document.createElement('div');
        this.div.classList.add('bullet');
        this.div.classList.add(this.dir);
        wrap.appendChild(this.div);

        this.move();
    }
    setPosition(left,top){
        this.left = left;
        this.top = top;
        this.div.style.left = this.left + 'px';
        this.div.style.top = this.top + 'px';
    }
    move(){
        this.timer = setInterval(() => {
            // 根据方向判断
            switch(this.dir){
                case 'left':
                    this.left-=this.seepd;
                    break;
                case 'right':
                    this.left+=this.seepd;
                    break;
                case 'top':
                    this.top-=this.seepd;
                    break;
                case 'bottom':
                    this.top+=this.seepd;
                    break;
            }

            this.setPosition(this.left,this.top);
            typeof this.onmove === 'function' && this.onmove();
        }, 16);
    }
    /**
     * 碰撞检测
     */
    collision(arr){
        // 当前子弹的中心点坐标
        let p1 = {
            x:this.left + this.width / 2,
            y:this.top + this.height / 2
        }

        for(let i = 0; i < arr.length; i++){
            // 每个元素的中心点
            let p2 = {
                x:arr[i].left + arr[i].width / 2,
                y:arr[i].top + arr[i].height / 2
            }

            // 当前元素与数组中的元素是碰撞的就把这个元素返回出去 正负10之间
            if(p1.x > p2.x - 10 && p1.x < p2.x + 10 && p1.y > p2.y - 10 && p1.y < p2.y + 10){
                return arr[i];
            }
        }
    }
    /**
     * 碰撞销毁
     */
    desctory(){
        clearInterval(this.timer);
        // 删除当前div
        this.div.remove();
    }
}